<template>
  <div>
    <t-dialog
        placement="center"
        width="680"
        v-model:visible="visible"
        :header="props.dialogTitle"
        :onClose="onClose"
        destroy-on-close
    >
      <template #body>
        <t-form
            ref="form"
            :data="formData"
            :rules="rules"
            :layout="'inline'"
            scroll-to-first-error="smooth"
            :label-width="90"
            @submit="onSubmit"
        >
          <t-form-item label="上级菜单" name="parentId">
            <t-tree-select
                v-model="formData.parentId"
                :data="menuOptions"
                clearable
                :filter="filterFunction"
                placeholder="请选择上级菜单" />
          </t-form-item>

          <t-form-item label="菜单类型" name="type">
            <t-radio-group v-model="formData.type" @change="onChange">
              <t-radio value="0">目录</t-radio>
              <t-radio value="1">菜单</t-radio>
              <t-radio value="2">按钮</t-radio>
            </t-radio-group>
          </t-form-item>

<!--          <t-space class="f_space" style="gap: 10px">-->
            <t-form-item label="菜单名称" name="menuName" style="width: 50%">
              <t-input v-model="formData.menuName" placeholder="请输入菜单名称"></t-input>
            </t-form-item>
            <t-form-item label="显示排序" name="sort" style="width: 50%">
              <t-input-number v-model="formData.sort" auto-width theme="column" :min="0" />
            </t-form-item>
<!--          </t-space>-->

<!--          <t-space class="s_space" style="gap: 10px">-->
            <t-form-item name="path" style="width: 50%;" v-if="formData.type !== '2'" :requiredMark="true" class="c_half_form_item">
              <span slot="label" class="c_label">
                <t-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头">
                  <InfoCircleIcon></InfoCircleIcon>
                </t-tooltip>
                <span>路由地址</span>
              </span>
              <t-input v-model="formData.path" placeholder="请输入路由地址"></t-input>
            </t-form-item>

            <t-form-item name="component" style="width: 50%;" v-if="formData.type === '1'" class="c_half_form_item">
              <span slot="label" class="c_label">
                <t-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下">
                  <InfoCircleIcon></InfoCircleIcon>
                </t-tooltip>
                <span>组件路径</span>
              </span>
              <t-input v-model="formData.component" placeholder="请输入组件路径"></t-input>
            </t-form-item>
<!--          </t-space>-->

<!--          <t-space class="f_space" style="gap: 10px" v-if="formData.type !== '2'">-->
            <t-form-item label="显示菜单" name="hidden" style="width: 50%;">
              <t-radio-group v-model="formData.hidden" @change="">
                <t-radio :value="0">是</t-radio>
                <t-radio :value="1">否</t-radio>
              </t-radio-group>
            </t-form-item>
            <t-form-item label="菜单图标" name="icon" style="width: 50%;" v-if="formData.type === '0'">
              <t-input v-model="formData.icon" placeholder="请输入图标名称"></t-input>
            </t-form-item>
<!--          </t-space>-->

<!--          <t-space class="t_space" style="gap: 10px" v-if="formData.type !== '0'">-->
            <t-form-item name="perms" style="width: 50%;" class="c_half_form_item">
              <span slot="label" class="c_label">
                <t-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)">
                  <InfoCircleIcon></InfoCircleIcon>
                </t-tooltip>
                <span>权限字符</span>
              </span>
              <t-input v-model="formData.perms" placeholder="请输入权限字符"></t-input>
            </t-form-item>
<!--          </t-space>-->

          <t-form-item class="f_btn">
            <t-space size="small">
              <t-button theme="default" variant="base" @click="handleCancel" >取消</t-button>
              <t-button theme="primary" type="submit">保存</t-button>
            </t-space>
          </t-form-item>
        </t-form>
      </template>
    </t-dialog>
  </div>
</template>

<script lang="jsx" setup>
import {nextTick, reactive, ref, watch} from "vue";
import {
  menuSelect,
  newMenu,
  menuInfo
} from '@/api/system/menu.js'
import { MessagePlugin } from 'tdesign-vue-next';
import { InfoCircleIcon } from 'tdesign-icons-vue-next';
import {editMenu} from "../../../api/system/menu";

const emits = defineEmits()
const props = defineProps({
  visibleDialog: {
    type: Boolean,
    default: false
  },
  dialogTitle: {
    type: String,
    default: ''
  },
  closeDialog: {
    type: Function,
    default: () => {}
  },
  isNewItem: {
    type: Boolean,
    default: true
  },
  rowData: {
    type: Object,
    default: {}
  }
})

const visible = ref(false)
watch(() => props.visibleDialog, (newVal) => {
  visible.value = newVal
  if(newVal.toString() === 'true') {
    getSelectData()
  }
})

const rules = {
  parentId: [{required: true, message: '请选择上级菜单', type: 'warning', trigger: 'change'}],
  menuName: [{required: true, message: '菜单名称不能为空', type: 'warning', trigger: 'blur'}],
  sort: [{required: true, message: '菜单顺序不能为空', type: 'warning', trigger: 'blur'}],
  path: [{required: true, message: '路由地址不能为空', type: 'warning', trigger: 'blur'}],
}
const formData = reactive({
  parentId: '',
  type: '0',
  menuName: '',
  sort: '',
  path: '',
  component: '',
  perms: '',
  icon: '',
  hidden: 0, // 0:展示 ｜ 1:隐藏
})
const form = ref(null);

// 菜单选择数据
let menuOptions = ref()
const getSelectData = () => {
  nextTick(() => {
    menuSelect().then(res => {

      // 解决 tree-select 回显 id 不回显 label 问题
      function toStr(ary) {
        ary.forEach(item => {
          item.label = item.menuName
          item.value = item.id
          if(item.children && item.children.length > 0) {
            toStr(item.children)
          }
        })
      }
      toStr(res.data)
      menuOptions.value = res.data

      // 设置默认选中上级菜单
      if(Object.keys(props.rowData).length === 0) {
        formData.parentId = menuOptions.value[0].id
      } else {
        if(props.isNewItem) { formData.parentId = props.rowData['id'] }
      }

      // 编辑调用详情接口
      if(!props.isNewItem) {
        menuInfo(props.rowData['id']).then(res => {
          console.log('xiang qing', res)
          if(res.code === 0) {
            formData.id = res.data.id
            formData.parentId = res.data.parentId
            formData.type = res.data.type.toString()
            formData.menuName = res.data.menuName
            formData.sort = res.data.sort
            formData.path = res.data.path
            formData.component = res.data.component
            formData.perms = res.data.perms
            formData.icon = res.data.icon
            formData.hidden = res.data.hidden
          }
        }).catch(error => {
          console.log(error)
        })
      }
    })
  })
}
// 菜单过滤
const filterFunction = (searchText, node) => {
  console.log(searchText, node)
  return node.data.menuName.indexOf(searchText) >= 0;
};

// 提交form
const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    if(props.isNewItem) { // 新增
      if(formData.id) delete formData.id
      newMenu(formData).then(res => {
        if(res.code === 0) {
          MessagePlugin.success('添加成功！');
          handleCancel()
          form.value.reset()
          formData.type = '0'
        }
      })
    } else { // 编辑
      editMenu(formData).then(res => {
        if(res.code === 0) {
          MessagePlugin.success('修改成功！');
          handleCancel()
        }
      })
    }
    console.log('formData', formData)
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

const onChange = (value, context) => {
  console.log(value, context)
}
// 重置 关闭dialog
const handleCancel = () => {
  form.value.reset()
  formData.type = '0'
  formData.hidden = 0
  emits('closeDialog', false)
};
const onClose = () => {
  form.value.reset()
  formData.type = '0'
  formData.hidden = 0
  emits('closeDialog', false)
}
</script>

<style lang="scss" scoped>
.c_half_form_item {
  width: 50% !important;
  :deep(.t-form__label) {
    //width: 90px !important;
    display: none !important;
  }
  :deep(.t-form__controls) {
    margin-left: 0 !important;
    width: calc(100%) !important;
    .c_label {
      width: 90px;
      text-align: right;
      padding-right: 10px;
    }
    .t-input__wrap {
      width: calc(100% - 90px);
    }
  }
}
:deep(.t-dialog) {
  padding: 21px 21px 5px 21px;
  .t-dialog__body {
    padding-top: 22px;
  }
  .t-dialog__footer {
    display: none;
  }
}
:deep(.t-form) {
  .t-form__item {
    width: 100%;
    margin-right: 0;
    .t-input-number {
      width: 100% !important;
      .t-input__wrap {
        width: 100%;
      }
    }
  }
  .t-form__label {
    padding-right: 10px;
  }
  .f_space {
    width: 100%;
  }
  .s_space {
    width: 100%;
    .t-space-item {
      width: calc(50% - 5px);
    }
    .t-form__label {
      width: 0 !important;
      padding-right: 10px;
    }
    .t-input__extra {
      padding-left: 80px;
    }
    .t-form__controls {
      margin-left: 0 !important;
      .c_label {
        display: flex;
        width: 110px;
        align-items: center;
        svg {
          height: 0.8em;
          width: 0.8em;
          margin-right: 4px;
        }
      }
    }
  }
  .t_space {
    width: 100%;
    .t-space-item {
      width: calc(50% - 5px);
    }
    .t-form__label {
      display: none;
    }
    .t-form__controls {
      margin-left: 0 !important;
      .c_label {
        display: flex;
        width: 126px;
        align-items: center;
        justify-content: right;
        padding-right: 10px;
        svg {
          height: 0.8em;
          width: 0.8em;
          margin-right: 4px;
        }
      }
    }
  }
  .f_btn {
    margin-top: 18px;
    .t-form__controls-content {
      .t-space {
        margin-left: auto;
        .t-button--theme-default {
          background-color: white;
          border: none;
          width: 60px;
          height: 28px;
        }
        .t-button--theme-primary {
          width: 60px;
          height: 28px;
          opacity: 1;
          border-radius: 3px;
          background: rgba(30, 117, 254, 1);
        }
      }
    }
  }
}
</style>
